package com.easychat.controller;

import com.easychat.annotation.LxdLog;
import com.easychat.entity.constants.Constants;
import com.easychat.entity.constants.RedisConstants;
import com.easychat.entity.dto.SysSettingDto;
import com.easychat.entity.dto.TokenUserInfoDto;
import com.easychat.entity.po.UserInfo;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.entity.vo.UserInfoVo;
import com.easychat.exception.BusinessException;
import com.easychat.redis.RedisCache;
import com.easychat.redis.RedisComponent;
import com.easychat.service.UserInfoService;
import com.wf.captcha.ArithmeticCaptcha;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author Dongdong
 * @注释
 */

@RestController("accountController")
@RequestMapping("/account")
@Validated//校验
public class AccountController extends ABaseController {

    private static final Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private RedisCache redis;
    @Autowired
    private UserInfoService userInfoService;
    @Resource
    private RedisComponent redisComponent;

    /**
     * 获取验证码
     * @return
     */
    @RequestMapping("/checkCode")
    public ResponseVO checkCode() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 42);
        String code = captcha.text(); // 获取运算的公式：3+2=?
        String checkCodeKey = UUID.randomUUID().toString();// 验证码的唯一标识uuid
        String checkCodebase64 = captcha.toBase64();//验证码图片
        logger.info("验证码是{}", code);
        redis.setCacheObject(RedisConstants.REDIS_KEY_CHECK_CODE + checkCodeKey, code, RedisConstants.REDIS_EXPIRE_1MIN, TimeUnit.MINUTES);//将code 存入Redis
        HashMap<String, String> result = new HashMap<>();
        result.put("checkCode", checkCodebase64);
        result.put("checkCodeKey", checkCodeKey);
        return getSuccessResponseVO(result);
    }

    /**
     * 注册
     *
     * @param checkCodeKey 验证码的唯一标识uuid
     * @param checkCode     验证码答案
     * @return
     */
    @PostMapping("/register")
    @LxdLog
    public ResponseVO register(@NotEmpty String checkCodeKey,
                               @NotEmpty @Email String email,
                               @NotEmpty String password,
                               @NotEmpty String nickName,
                               @NotEmpty String checkCode) {

        try {
            //1. 判断验证码是否正确
            if (!checkCode.equals(redis.getCacheObject(RedisConstants.REDIS_KEY_CHECK_CODE + checkCodeKey))) {
                throw new BusinessException("验证码不正确！");
            }
            //2.进行注册
            userInfoService.register(email, password, nickName);
        } finally {
            //3.从redis中删除，防止用户一直刷
            redis.deleteObject(RedisConstants.REDIS_KEY_CHECK_CODE + checkCodeKey);
        }
        return getSuccessResponseVO("注册成功");

    }

    /**
     * 登录
     * @param checkCodeKey 验证码的唯一标识uuid
     * @param checkCode     验证码答案
     * @return
     */
    @PostMapping("/login")
    @LxdLog
    public ResponseVO login(@NotEmpty String checkCodeKey,// uuid
                            @NotEmpty @Email String email,
                            @NotEmpty String password,
                            @NotEmpty String checkCode) {

        try {
            // 判断验证码是否正确
            if (!checkCode.equals(redis.getCacheObject(RedisConstants.REDIS_KEY_CHECK_CODE + checkCodeKey))) {
                throw new BusinessException("验证码不正确！");
            }
            //进行登录，生成token
            TokenUserInfoDto tokenUserInfoDto = userInfoService.login(email, password);

            UserInfo userinfo = userInfoService.getUserInfoByUserId(tokenUserInfoDto.getUserId());

            //组装UserInfoVo
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(userinfo, userInfoVo);
            userInfoVo.setToken(tokenUserInfoDto.getToken());
            userInfoVo.setAdmin(tokenUserInfoDto.getAdmin());

            return getSuccessResponseVO(userInfoVo);
        } finally {
            //从redis中删除，防止用户一直刷
            redis.deleteObject(RedisConstants.REDIS_KEY_CHECK_CODE + checkCodeKey);
        }

    }

    /**
     * 获取系统设置
     * @return
     */
    @RequestMapping("/getSysSetting")
    public ResponseVO getSysSetting() {
        SysSettingDto sysSettingDto = redisComponent.getSysSettingDto();

        return getSuccessResponseVO(sysSettingDto);
    }
}



